using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Tools
{
    public class PluginFactory
    {

        private static PluginFactory instance = null;

        public static PluginFactory Instance
        {
            get
            {
                if (instance == null) instance = new PluginFactory();
                return instance;
            }
        }

        private Dictionary<string, string> names = new Dictionary<string,string>();
        private Dictionary<string, Type> types = new Dictionary<string,Type>();

        public object NewInstance(string keyName)
        {
            Type type;
            if (!types.TryGetValue(keyName, out type))
            {
                string typeName;
                if (!names.TryGetValue(keyName, out typeName)) throw new Exception("unable to find type for key '"+keyName+"'");
                type = Type.GetType(typeName,true);
                types.Add(keyName, type);
            }
            return Activator.CreateInstance(type);
            //ConstructorInfo constructor = type.GetConstructor(new Type[0]);
            //return constructor.Invoke(new object[0]);
        }

        public object NewInstance(Type type)
        {
            return NewInstance(type.FullName);
        }

        public void Register(Type interfaceType, Type implementationType) { Register(interfaceType.FullName, implementationType.AssemblyQualifiedName); }
        public void Register(string interfaceName, Type implementationType) { Register(interfaceName, implementationType.AssemblyQualifiedName); }
        public void Register(Type interfaceType, string typeName) { Register(interfaceType.FullName, typeName); }
        public void Register(string interfaceName, string typeName) { names.Add(interfaceName, typeName); }
        public void Unregister(string interfaceName) { names.Remove(interfaceName); types.Remove(interfaceName); }

    }
}
